package com.wechat.order.controller.PayController;

import com.google.common.collect.Maps;
import com.lly835.bestpay.model.PayResponse;
import com.wechat.order.dto.OrderDTO;
import com.wechat.order.enums.ResultEnum;
import com.wechat.order.exception.SellException;
import com.wechat.order.service.orderService.OrderService;
import com.wechat.order.service.PayService.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 微信支付控制层
 * Created by zzy on 2017/12/18.
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;

    @RequestMapping("/create")
    public ModelAndView crete(@RequestParam("orderId") String orderId,
                              @RequestParam("returnUrl") String returnUrl){
        //1、查询订单

        PayResponse payResponse=new PayResponse();
        try {
            OrderDTO orderDTO=orderService.findOne(orderId);
            if (orderDTO == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            payResponse= payService.create(orderDTO);
        }catch (Exception e){
            log.info(e.getMessage(),e);
        }
        Map<String,Object> map= Maps.newHashMap();
        map.put("payResponse",payResponse);
        map.put("returnUrl",returnUrl);
        //返回预付单信息，调用js请求微信支付
        return new ModelAndView("pay/create",map);

    }

    /**
     * 微信支付返回结果
     * @param notifyData
     * @return
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData){
        payService.notify(notifyData);
        //返回给微信处理结果（固定模板）
        return  new ModelAndView("pay/success");
    }
}
